<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片上传测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }
        
        .content {
            padding: 40px;
        }
        
        .upload-area {
            border: 3px dashed #667eea;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            margin-bottom: 30px;
            transition: all 0.3s ease;
            background: #f8f9ff;
        }
        
        .upload-area:hover {
            border-color: #764ba2;
            background: #f0f2ff;
        }
        
        .upload-area.dragover {
            border-color: #764ba2;
            background: #e8ebff;
            transform: scale(1.02);
        }
        
        .upload-icon {
            font-size: 4em;
            color: #667eea;
            margin-bottom: 20px;
        }
        
        .upload-text {
            font-size: 1.2em;
            color: #666;
            margin-bottom: 20px;
        }
        
        .file-input {
            display: none;
        }
        
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            font-size: 1.1em;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 10px;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.2);
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .status {
            margin: 20px 0;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            font-weight: bold;
        }
        
        .status.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .status.info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .images-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 30px;
        }
        
        .image-item {
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            overflow: hidden;
            transition: transform 0.3s ease;
        }
        
        .image-item:hover {
            transform: translateY(-5px);
        }
        
        .image-item img {
            width: 100%;
            height: 150px;
            object-fit: cover;
        }
        
        .image-info {
            padding: 15px;
        }
        
        .image-name {
            font-weight: bold;
            margin-bottom: 5px;
            word-break: break-all;
        }
        
        .image-size {
            color: #666;
            font-size: 0.9em;
        }
        
        .server-info {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
            text-align: center;
        }
        
        .server-status {
            display: inline-block;
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: bold;
            margin: 5px;
        }
        
        .server-status.online {
            background: #d4edda;
            color: #155724;
        }
        
        .server-status.offline {
            background: #f8d7da;
            color: #721c24;
        }
        
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-left: 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📸 图片上传测试</h1>
            <p>测试后台图片上传功能</p>
        </div>
        
        <div class="content">
            <div class="server-info">
                <h3>服务器状态</h3>
                <div id="serverStatus">
                    <span class="loading"></span>
                    <span>正在检测服务器...</span>
                </div>
            </div>
            
            <div class="upload-area" id="uploadArea">
                <div class="upload-icon">📁</div>
                <div class="upload-text">
                    拖拽图片到这里或点击选择文件
                </div>
                <input type="file" id="fileInput" class="file-input" accept="image/*" multiple>
                <button class="btn" onclick="document.getElementById('fileInput').click()">选择图片</button>
            </div>
            
            <div id="status" class="status hidden"></div>
            
            <div id="uploadSection" class="hidden">
                <h3>上传进度</h3>
                <div id="progressContainer"></div>
            </div>
            
            <div id="imagesSection" class="hidden">
                <h3>已上传的图片</h3>
                <div id="imagesGrid" class="images-grid"></div>
            </div>
        </div>
    </div>

    <script>
        class ImageUploader {
            constructor() {
                this.uploadArea = document.getElementById('uploadArea');
                this.fileInput = document.getElementById('fileInput');
                this.status = document.getElementById('status');
                this.uploadSection = document.getElementById('uploadSection');
                this.progressContainer = document.getElementById('progressContainer');
                this.imagesSection = document.getElementById('imagesSection');
                this.imagesGrid = document.getElementById('imagesGrid');
                this.serverStatus = document.getElementById('serverStatus');
                
                this.init();
            }
            
            init() {
                this.setupEventListeners();
                this.checkServerStatus();
                this.loadImages();
            }
            
            setupEventListeners() {
                // 拖拽事件
                this.uploadArea.addEventListener('dragover', (e) => {
                    e.preventDefault();
                    this.uploadArea.classList.add('dragover');
                });
                
                this.uploadArea.addEventListener('dragleave', () => {
                    this.uploadArea.classList.remove('dragover');
                });
                
                this.uploadArea.addEventListener('drop', (e) => {
                    e.preventDefault();
                    this.uploadArea.classList.remove('dragover');
                    this.handleFiles(e.dataTransfer.files);
                });
                
                // 文件选择事件
                this.fileInput.addEventListener('change', (e) => {
                    this.handleFiles(e.target.files);
                });
            }
            
            async checkServerStatus() {
                try {
                    const response = await fetch('/api/images');
                    if (response.ok) {
                        this.serverStatus.innerHTML = '<span class="server-status online">✅ 服务器在线</span>';
                        return true;
                    }
                } catch (error) {
                    console.log('服务器检测失败:', error);
                }
                
                this.serverStatus.innerHTML = '<span class="server-status offline">❌ 服务器离线</span>';
                return false;
            }
            
            async loadImages() {
                try {
                    const response = await fetch('/api/images');
                    if (response.ok) {
                        const data = await response.json();
                        this.displayImages(data.data || data.images || []);
                    }
                } catch (error) {
                    console.log('加载图片失败:', error);
                }
            }
            
            displayImages(images) {
                if (images.length === 0) {
                    this.imagesSection.classList.add('hidden');
                    return;
                }
                
                this.imagesSection.classList.remove('hidden');
                this.imagesGrid.innerHTML = images.map(image => `
                    <div class="image-item">
                        <img src="${image.url || '/uploads/' + image.name}" alt="${image.name}" onerror="this.src=''">">
                        <div class="image-info">
                            <div class="image-name">${image.name}</div>
                            <div class="image-size">${this.formatFileSize(image.size)}</div>
                        </div>
                    </div>
                `).join('');
            }
            
            formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
            
            handleFiles(files) {
                if (files.length === 0) return;
                
                this.uploadFiles(Array.from(files));
            }
            
            async uploadFiles(files) {
                this.showStatus('开始上传图片...', 'info');
                this.uploadSection.classList.remove('hidden');
                this.progressContainer.innerHTML = '';
                
                const serverOnline = await this.checkServerStatus();
                if (!serverOnline) {
                    this.showStatus('服务器离线，无法上传图片', 'error');
                    return;
                }
                
                const uploadPromises = files.map((file, index) => this.uploadFile(file, index));
                const results = await Promise.allSettled(uploadPromises);
                
                const successful = results.filter(r => r.status === 'fulfilled').length;
                const failed = results.filter(r => r.status === 'rejected').length;
                
                if (failed === 0) {
                    this.showStatus(`✅ 所有图片上传成功！共 ${successful} 张`, 'success');
                } else {
                    this.showStatus(`⚠️ 上传完成：成功 ${successful} 张，失败 ${failed} 张`, 'error');
                }
                
                // 重新加载图片列表
                setTimeout(() => this.loadImages(), 1000);
            }
            
            async uploadFile(file, index) {
                const progressItem = document.createElement('div');
                progressItem.style.cssText = 'margin: 10px 0; padding: 10px; background: #f8f9ff; border-radius: 5px;';
                progressItem.innerHTML = `
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <span>${file.name}</span>
                        <span class="progress-text">0%</span>
                    </div>
                    <div style="width: 100%; background: #e0e0e0; border-radius: 10px; margin-top: 5px;">
                        <div class="progress-bar" style="width: 0%; height: 5px; background: #667eea; border-radius: 10px; transition: width 0.3s;"></div>
                    </div>
                `;
                this.progressContainer.appendChild(progressItem);
                
                return new Promise((resolve, reject) => {
                    const formData = new FormData();
                    formData.append('image', file);
                    
                    const xhr = new XMLHttpRequest();
                    
                    xhr.upload.addEventListener('progress', (e) => {
                        if (e.lengthComputable) {
                            const percentComplete = Math.round((e.loaded / e.total) * 100);
                            const progressBar = progressItem.querySelector('.progress-bar');
                            const progressText = progressItem.querySelector('.progress-text');
                            progressBar.style.width = percentComplete + '%';
                            progressText.textContent = percentComplete + '%';
                        }
                    });
                    
                    xhr.addEventListener('load', () => {
                        if (xhr.status === 200) {
                            const response = JSON.parse(xhr.responseText);
                            if (response.success) {
                                progressItem.style.background = '#d4edda';
                                resolve(response);
                            } else {
                                progressItem.style.background = '#f8d7da';
                                reject(new Error(response.message || '上传失败'));
                            }
                        } else {
                            progressItem.style.background = '#f8d7da';
                            reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`));
                        }
                    });
                    
                    xhr.addEventListener('error', () => {
                        progressItem.style.background = '#f8d7da';
                        reject(new Error('网络错误'));
                    });
                    
                    // 尝试不同的上传端点
                    const endpoints = ['/api/upload', '/api/upload-image', '/upload'];
                    let currentEndpoint = 0;
                    
                    const tryUpload = () => {
                        if (currentEndpoint >= endpoints.length) {
                            reject(new Error('所有上传端点都失败了'));
                            return;
                        }
                        
                        xhr.open('POST', endpoints[currentEndpoint]);
                        xhr.send(formData);
                    };
                    
                    xhr.addEventListener('error', tryUpload);
                    tryUpload();
                });
            }
            
            showStatus(message, type) {
                this.status.textContent = message;
                this.status.className = `status ${type}`;
                this.status.classList.remove('hidden');
                
                setTimeout(() => {
                    this.status.classList.add('hidden');
                }, 5000);
            }
        }
        
        // 初始化上传器
        document.addEventListener('DOMContentLoaded', () => {
            new ImageUploader();
        });
    </script>
</body>
</html>